package handlers

import (
	"fmt"
	"io"
	"luntan/pkg/database"
	"net/http"
	"strings"
)

func Login(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

	msg := Message{Msg: "login success"}
	name := req.URL.Query().Get("name")
	pwd := req.URL.Query().Get("pwd")
	// fmt.Println(name, pwd)

	session, _ := Session_store.Get(req, "session-luntan")
	sid, _ := session.Values["sid"].(string)
	if sid == "" {
		msg.Msg = "sid is empty"
		msg.Status = -1
		return
	}

	nameInSession, _ := session.Values["name"].(string)
	pwdInSession, _ := session.Values["pwd"].(string)

	// get from fe
	buf, err := io.ReadAll(req.Body)
	if err != nil || buf == nil {
		msg.Status = -1
		fmt.Println("reqwrong")
		msg.Msg = "invalid/nil request param"
		return
	}
	// jsonMap := make(map[string]interface{})
	// err = json.Unmarshal(buf, &jsonMap)
	// if err != nil {
	// 	msg.Status = -400
	// 	fmt.Println("jsonwrong", err.Error())
	// 	msg.Msg = err.Error()
	// 	return
	// }

	defer func() {
		for k, v := range Connections {
			if k != sid {
				continue
			}
			v.Account = name
			break
		}
		Resp(w, &msg)
	}()

	if name == "" && nameInSession != "" {
		name = nameInSession
	} else {
		nameInSession = name
	}
	if pwd == "" && pwdInSession != "" {
		pwd = pwdInSession
	} else {
		pwdInSession = pwd
	}
	if name == "" || pwd == "" {
		msg.Status = -500
		msg.Msg = "invalid/empty user/cert"
		return
	}
	//是否有用户
	rows, err := database.SelectUser(name, pwd)
	if err != nil {
		msg.Status = -1
		msg.Msg = err.Error()
		return
	}
	if !rows.Next() {
		err := database.InsertUser(name, pwd)
		if err != nil {
			msg.Status = -600
			msg.Msg = err.Error()
			if strings.Contains(msg.Msg, "duplicate key") {
				msg.Status = -603
				msg.Msg = "invalid user name/password"
				return
			}
		} else {
			msg.Msg = "new user created"
		}
	}

	if name == "" || pwd == "" {
		msg.Status = -500
		msg.Msg = "invalid/empty name/pwd"
		return
	}
	session.Values["name"] = name
	session.Values["pwd"] = pwd
	session.Values["authed"] = true
	session.Save(req, w)
}
